//
//  ViewController.swift
//  day09
//
//  Created by 杨绍鑫 on 2018/9/20.
//  Copyright © 2018年 crcnet. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var scrollVIew: UIScrollView!
    
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var imageViewTrailConstraint: NSLayoutConstraint!
    @IBOutlet weak var imageViewleadConstraint: NSLayoutConstraint!
    @IBOutlet weak var imageViewBoConstraint: NSLayoutConstraint!
    @IBOutlet weak var imageViewTopConstraint: NSLayoutConstraint!
    override func viewDidLoad() {
        super.viewDidLoad()
        scrollVIew.delegate = self
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }
    
    fileprivate func updateMinZoomScaleForSize(size:CGSize){
        
        let sw = size.width / imageView.frame.size.width
        let sh = size.height / imageView.frame.size.height
        
        let scal = min(sw, sh)
        
        scrollVIew.maximumZoomScale = 3.0
        scrollVIew.minimumZoomScale = 1.0
        scrollVIew.zoomScale = scal
        
    }
    
    fileprivate func updateConstanForSize(size:CGSize){
        ////将图像垂直居中，从视图高度减去imageView的高度并分成两半，这个值用作顶部和底部imageView的约束
        
        print(imageView.frame)
        let yOffset = max(0, (size.height - imageView.frame.height) / 2)
        imageViewTopConstraint.constant = yOffset
        imageViewBoConstraint.constant = yOffset
        
        ////根据宽度计算imageView前后约束的偏移量
        let xOffset = max(0, (size.width - imageView.frame.width) / 2)
        imageViewleadConstraint.constant = xOffset
        imageViewTrailConstraint.constant = xOffset
        
        view.layoutIfNeeded()
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        updateMinZoomScaleForSize(size: view.frame.size)
    }

}

extension ViewController: UIScrollViewDelegate{
    
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
      self.updateConstanForSize(size: view.frame.size)
    }
    
    
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }
}
